interface HTMLElementWithTimeout extends HTMLElement {
	__timeoutId__?: number | ReturnType<typeof setInterval>
}

class Time {
	// 获取当前时间戳
	getUnix(): number {
		return new Date().getTime()
	}

	// 获取今天 0 点 0 分 0 秒的时间戳
	getTodayUnix(): number {
		const date = new Date()
		date.setHours(0, 0, 0, 0)
		return date.getTime()
	}

	// 获取今年 1 月 1 日 0 点 0 秒的时间戳
	getYearUnix(): number {
		const date = new Date()
		date.setMonth(0, 1)
		date.setHours(0, 0, 0, 0)
		return date.getTime()
	}

	// 获取标准年月日
	getLastDate(time: number): string {
		const date = new Date(time)
		const month = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
		const day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
		return `${date.getFullYear()}-${month}-${day}`
	}

	// 转换时间
	getFormateTime(timestamp: number): string {
		const timestampDate = new Date(timestamp)
		const now = this.getUnix()
		const today = this.getTodayUnix()
		const timer = (now - timestampDate.getTime()) / 1000
		let tip = ''

		if (timer <= 0) {
			tip = lang.global.t('time.now')
		} else if (timer < 60) {
			tip = lang.global.t('time.now')
		} else if (timer < 3600) {
			tip = `${Math.floor(timer / 60)} ${lang.global.t('time.minutes')}`
		} else if (timer < 86400 && timestampDate.getTime() - today >= 0) {
			tip = `${Math.floor(timer / 3600)} ${lang.global.t('time.hours')}`
		} else if (timer / 86400 <= 31) {
			tip = `${Math.ceil(timer / 86400)} ${lang.global.t('time.days')}`
		} else {
			tip = this.getLastDate(timestampDate.getTime())
		}
		return tip
	}
}

export default {
	mounted(el: HTMLElementWithTimeout, binding: { value: number; modifiers: { tip?: boolean } }) {
		const { value, modifiers } = binding
		if (!value) return

		const timeInstance = new Time()
		let modifiedValue = value
		if (value.toString().length === 10) {
			modifiedValue *= 1000
		}

		// 初始化展示
		if (modifiers.tip) {
			el.innerHTML = timeInstance.getFormateTime(modifiedValue)
			el.__timeoutId__ = setInterval(() => {
				el.innerHTML = timeInstance.getFormateTime(modifiedValue)
			}, 60000)
		} else {
			const format = el.getAttribute('format') || undefined
			el.innerHTML = tool.dateFormat(modifiedValue, format)
		}
	},

	unmounted(el: HTMLElementWithTimeout) {
		// 清除定时器，防止内存泄漏
		if (el.__timeoutId__) {
			clearInterval(el.__timeoutId__)
		}
	}
}
